import { ShelfPackage } from '@/api/Shelf';
import { useReactive } from 'ahooks';
import { App, Button, Drawer, Modal } from 'antd';
import { useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { LeftClassTree } from '../../../LeftClassTree';
import { ShelfAIModalContent, ShelfAIRef, ShelfUpperModalContent, ShelfUpperRef } from '../../../UpperContent';
import { PackageDetail, PackageDetailPorps } from '../../Detail';
import { PackageInfo } from '../interface';
type RecordType = ShelfPackage;

interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value: PackageInfo): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}

export function List({ onAddEdit }: ListPorps) {
  const [columns] = useState<YmColumnsType<RecordType>>([
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      width: 200,
    },
    {
      key: '_operate',
      title: '操作',
      width: 140,
    },
  ]);
  const [extraParams, setExtraParams] = useState<{ classId?: string; parClassId?: string }>({
    classId: undefined,
    parClassId: undefined,
  });
  const upperRef = useRef<ShelfUpperRef>(null);
  const AIRef = useRef<ShelfAIRef>(null);
  const upperExtram = useReactive<{ guid?: string; aiLearnClassification?: number }>({
    guid: undefined,
    aiLearnClassification: 0,
  });
  const { modal } = App.useApp();
  const detailsPorps = useReactive<{ props?: PackageDetailPorps }>({});
  const [treeRefresh, setTreeRefresh] = useState<number>();
  const refreshTableAndTree = () => {
    setExtraParams((v) => ({ ...v }));
    setTreeRefresh(Math.random());
  };
  return (
    <div className="safe_boss_pagelr">
      <div className="safe_boss_page_left">
        <LeftClassTree
          value={extraParams.classId}
          onSelect={(classId, parClassId) => {
            setExtraParams((p) => ({ ...p, classId, parClassId }));
          }}
          refreshDeps={[treeRefresh]}
        ></LeftClassTree>
      </div>
      <div className="safe_boss_page_right">
        <YmTable
          searchForm={{
            formItems: [
              {
                label: '名称',
                name: 'packageName',
                valueType: {
                  type: 'input',
                },
              },
            ],
          }}
          toolBar={{
            prefixNode: (
              <Button
                type="primary"
                onClick={() => {
                  onAddEdit?.(extraParams);
                }}
              >
                新增
              </Button>
            ),
          }}
          columns={columns}
          request={async ({ page }, form) => {
            const { current = 0, pageSize = 10 } = page ?? {};
            const data = await ShelfPackage.unShelfList(current, pageSize, { ...form, classId: extraParams.classId });
            return data;
          }}
          requestOptions={{
            reFreshDep: [extraParams],
            defaultPageSize: 20,
          }}
          rowKey="guid"
          operate={[
            {
              text: '编辑',
              key: 'edit',
              onClick(record) {
                onAddEdit?.({
                  packageId: record.guid,
                  packageName: record.name,
                  classId: record.classId,
                  parClassId: record.parClassId,
                  faceImg: record.cover,
                });
              },
            },
            {
              text: '详情',
              key: 'detail',
              onClick(record) {
                detailsPorps.props = {
                  guid: record.guid,
                  name: record.name,
                  createTime: record.createTime,
                };
              },
            },
            {
              text: '删除',
              key: 'delete',
              onClick(record) {
                modal.confirm({
                  title: '提示',
                  content: `确定要删除【${record.name}】吗`,
                  async onOk() {
                    await ShelfPackage.delete(record.guid);
                    refreshTableAndTree();
                  },
                });
              },
            },
            {
              text: '上架',
              key: 'listing',
              onClick(record) {
                upperExtram.guid = record.guid;
                upperExtram.aiLearnClassification = record.aiLearnClassification;
              },
            },
          ]}
        ></YmTable>
      </div>
      <Modal
        title="上架"
        width={1120}
        open={Boolean(upperExtram.guid)}
        onCancel={() => (upperExtram.guid = undefined)}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          const result =
            upperExtram.aiLearnClassification != 1 ? await upperRef.current?.submit() : await AIRef.current?.submit();
          await ShelfPackage.shelf.upper({ ...upperExtram, ...result });
          upperExtram.guid = undefined;
          upperExtram.aiLearnClassification = undefined;
          refreshTableAndTree();
        }}
      >
        <div style={{ maxHeight: '450px', overflowY: 'auto' }}>
          {upperExtram.aiLearnClassification != 1 ? (
            <ShelfUpperModalContent ref={upperRef}></ShelfUpperModalContent>
          ) : (
            <ShelfAIModalContent ref={AIRef}></ShelfAIModalContent>
          )}
        </div>
      </Modal>
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props)}
        title="详情"
        onClose={() => {
          detailsPorps.props = undefined;
        }}
      >
        <PackageDetail {...detailsPorps.props} />
      </Drawer>
    </div>
  );
}
